package com.blog.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.blog.mapper.SearchMapper;
import com.blog.pojo.Article;
import com.blog.pojo.ArticleEs;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RabbitListener(queues = "ESQueue")
public class ArticleConsumer {
    @Autowired
    private SearchMapper searchMapper;
    @RabbitHandler
    public void listener(Map map, Channel channel, Message message) throws IOException {
        try {
        String type = (String) map.get("type");
        if ("update".equals(type)) {
            Article article = (Article) map.get("article");
            String s = JSON.toJSONString(article);
            ArticleEs articleEs = JSON.parseObject(s, ArticleEs.class);
            searchMapper.save(articleEs);
        }
        if ("delete".equals(type)){
            int id = (int) map.get("id");
            searchMapper.deleteById(id);
        }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
}
